<template>
  <div style="display: flex;width: 100%;height: 100%;">
      <div style="flex: 1;height: 100%;overflow: auto;">
<!--          -->
<!--          <h3>{{search_global_branch}}</h3>-->

<!--     分店列表     -->
          <div v-for="item in branch_arr" class="branch_list" >

              <p style="text-align: left;
                        padding-top: 15px;
                        margin-left: 20px;
                        color: #555;
                        box-sizing: border-box">
                  <el-icon><location /></el-icon>
                  {{item.name}}
                  <el-icon class="branch_list_icon" @click="move_to_branch(item)"><Position /></el-icon>
              </p>
              <p class="branch_list_p">
                  <el-icon><ForkSpoon /></el-icon>
                  营业时间：{{item.workTimeStart}} - {{item.workTimeEnd}}
              </p>

              <p class="branch_list_p">
                  <el-icon><LocationInformation /></el-icon>
                  地点：{{item.address}}
              </p>
              <p class="branch_list_p">
                  <el-icon><Phone /></el-icon>
                  联系电话：{{item.phone}}
              </p>
              <el-button @click="enter_branch(item.id)" class="branch_list_b" style= "margin-left: 190px;width: 80px;height: 22px;margin-top: 0;" link type="info">进入餐厅</el-button>
          </div>
      </div>
      <div style="flex: 4;">
          <div id="map_container" style="height:100% ;width: 100%;">

          </div>
          <ul class="btn-wrap" style="z-index: 99;">
              <li class = "light btn" @click = make_flag_to_map>所有分店</li>
              <li class = "night btn" @click = "get_location_me">当前位置</li>
          </ul>
      </div>

  </div>
</template>

<script setup>

import {computed, inject, nextTick, onMounted, ref, watch} from "vue";
import {DrawControl, DrawScene, OperateEventType} from "bmap-draw";
import {ElMessage} from "element-plus";
import router from "@/router";
import axios from "axios";


//分店数组
const branch_arr = ref([])
//分店经纬度点
var branch_lngLat

//当前位置点经纬度
var local_point
//当前位置名称
var local_name
//当前位置标记
var local_mk

var myIcon = new BMapGL.Icon("/imgs/icon/my_location2.svg", new BMapGL.Size(35, 40));
var branchIcon = new BMapGL.Icon("/imgs/icon/branch_location.svg", new BMapGL.Size(36, 45));
var branchChangeIcon = new BMapGL.Icon("/imgs/icon/branch_location2.svg", new BMapGL.Size(35, 40));

//点击分店列表
const move_to_branch =(item)=> {
    //confirm(item.name)
    //confirm(item.lng)
    map.clearOverlays();
    branch_lngLat = new BMapGL.Point(item.lng,item.lat)
    let marker = new BMapGL.Marker(branch_lngLat,{icon:branchChangeIcon});        // 创建标注
    map.addOverlay(marker);
    map.panTo(branch_lngLat, 16);// 将标注添加到地图中
    marker.addEventListener("mouseover", function(){
        //alert("您点击了标注");
        var opts = {
            width: 250,     // 信息窗口宽度
            height: 100,    // 信息窗口高度
            title: "当前分店"  // 信息窗口标题
        }
        var infoWindow = new BMapGL.InfoWindow("<p id='info_window_p'></p><button id='info_window_b' style='border: 0;color: #fff;\n" +
            "    background-color: rgb(121,187,255);\n" +
            "    border-radius: 5px;\n" +
            "    padding: 3px 10px;\n" +
            "    line-height: 20px;\n" +
            "    font-size: 12px;\n" +
            "    text-decoration: none;\n" +
            "    font-family: Microsoft Yahei;\n" +
            "    cursor: pointer;" +
            "    margin-left:180px;'>进入</button>", opts);  // 创建信息窗口对象
        map.openInfoWindow(infoWindow, branch_lngLat);        // 打开信息窗口
        document.getElementById("info_window_p").innerHTML = item.name;
        document.getElementById("info_window_b").addEventListener("click",function (){
            enter_branch(item.id)
        });
    });
}
//给标记点添加点击监听事件
function markerAddEventLinter(branch_item,branch_marker){
    branch_marker.addEventListener("click", function(){
        //alert("您点击了标注");
        branch_lngLat = new BMapGL.Point(branch_item.lng,branch_item.lat)
        map.centerAndZoom(branch_lngLat,16)
        let opts = {
            width: 250,     // 信息窗口宽度
            height: 100,    // 信息窗口高度
            title: "当前分店"  // 信息窗口标题
        }
        let infoWindow = new BMapGL.InfoWindow("<p id='info_window_p'></p><button id='info_window_b' style='border: 0;color: #fff;\n" +
            "    background-color: rgb(121,187,255);\n" +
            "    border-radius: 5px;\n" +
            "    padding: 3px 10px;\n" +
            "    line-height: 20px;\n" +
            "    font-size: 12px;\n" +
            "    text-decoration: none;\n" +
            "    font-family: Microsoft Yahei;\n" +
            "    cursor: pointer;" +
            "    margin-left:180px;'>进入</button>", opts);  // 创建信息窗口对象
        map.openInfoWindow(infoWindow, branch_lngLat);        // 打开信息窗口

        setTimeout(function (){
            document.getElementById("info_window_p").innerHTML = branch_item.name;
            document.getElementById("info_window_b").addEventListener("click",function (){
                enter_branch(branch_item.id)
            });
        },10)

    });

}


//获取当前位置（浏览器定位）
function get_location_me(){
    var geolocation = new BMapGL.Geolocation();
    geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            map.clearOverlays(local_mk)
            local_mk = new BMapGL.Marker(r.point,{icon:myIcon});
            //local_mk.disableMassClear();//禁止覆盖物在map.clearOverlays方法中被清除
            map.addOverlay(local_mk);
            map.panTo(r.point);
            //alert('您的位置：' + r.point.lng + ',' + r.point.lat);
            local_point = new BMapGL.Point(r.point.lng,r.point.lat)
            get_location_me_name()
            map.centerAndZoom(local_point,18)//设置中心点和缩放级别
            local_mk.addEventListener("mouseover", function(){
                var opts = {
                    width: 250,     // 信息窗口宽度
                    height: 100,    // 信息窗口高度
                    title: "你当前所在位置"  // 信息窗口标题
                }
                var infoWindow = new BMapGL.InfoWindow(String(local_name), opts);  // 创建信息窗口对象
                map.openInfoWindow(infoWindow, local_point);        // 打开信息窗口
            });
        }
        else {
            //alert('当前位置信息获取失败' + this.getStatus());
        }
    });

}
//获取当前位置名称
function get_location_me_name(){
    //根据坐标点获得该地点的地址描述(逆地址解析)
    //创建地理编码实例
    var myGeo = new BMapGL.Geocoder();
    //根据当前坐标得到地址描述
    myGeo.getLocation(local_point, function(result){
        if (result){
            local_name=result.address
        }
    });
}

//将所有分店标记到地图上
const make_flag_to_map = ()=>{
    console.log('obj======>')
    console.log(branch_arr.value)
    //map.clearOverlays(local_mk)
    map.clearOverlays()
    if(branch_arr.value.length>0){
        for(let i=0;i<branch_arr.value.length;i++){
            let point = new BMapGL.Point(branch_arr.value[i].lng,branch_arr.value[i].lat)
            let marker = new BMapGL.Marker(point,{icon:branchIcon});
            markerAddEventLinter(branch_arr.value[i],marker)
            map.addOverlay(marker);//设置完监听事件之后再添加覆盖物，否则会报错：Cannot set properties of null (setting 'textContent')
        }
        map.centerAndZoom(new BMapGL.Point(branch_arr.value[0].lng,branch_arr.value[0].lat),13);
        //console.log(branch_arr.value[0].lng)
        //console.log(branch_arr.value[0].lat)
    }else{
        ElMessage.warning('当前搜索没有目标点')
    }

}

var map

//进入页面立即执行

onMounted(()=>{
  getBranchByStatus(branch_arr)
    //表示在DOM更新完毕后在执行，保证在存放地图的div创建完毕后再执行
    nextTick(()=>{
        //第七步：创建地图实例（注意不要导入）
        map = new BMapGL.Map("map_container")
        //第八步：设置地图的中心点坐标的经纬度，此处是天安门
        let point = new BMapGL.Point(116.4074,39.9024)
        //第九步：给上方创建好的地图对象设置中心点与缩放级别
        map.centerAndZoom(point,16)
        map.enableScrollWheelZoom();//启用滚轮放大缩小
        //添加控件
        let scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
        map.addControl(scaleCtrl);
        let zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
        map.addControl(zoomCtrl);
        let cityCtrl = new BMapGL.CityListControl();  // 添加城市列表控件
        map.addControl(cityCtrl);
        get_location_me()
        //make_flag_to_map(branch_arr.value)
    })
})

/*进入分店*/
const enter_branch = (id)=>{
    //router.push({path:'/meal',query:{id:id}})
    router.push('/meal')
    store.state.global_branch_Id=id//将分店id进行状态管理
}
/*根据输入框内容（名字或地址）搜索分店*/
const load_branch =(content)=>{
    if(content===''){
        getBranchs(branch_arr)
        return
    }
    axios.get(BASE_URL+'/v1/branch/selectByContent/'+content)
        .then((response)=>{
            if(response.data.code===2000){
                branch_arr.value=response.data.data
                ElMessage.success('分店已刷新')
                make_flag_to_map()
            }else{
                ElMessage.error(response.data.msg)
            }
        })
}


const store = inject('store')
const search_global_branch = computed(() => store.state.search_global)
//监视ref定义的【基本类型】数据
const stopWatch = watch(search_global_branch,(newValue,oldValue)=> {
    //console.log('变化了', newValue, oldValue)
    if (newValue === oldValue) {
        //如果没有变化，
        stopWatch()
    }else{
        load_branch(newValue)
    }
})

</script>

<style scoped>

.branch_list{
    width: 100%;
    height: 200px;
    margin-top: 5px;
    //border-bottom-style: dashed;
    //border-width: 0.01em;
    //cursor:pointer;
    background-image: linear-gradient(to right, #ace0f9 0%, #e7f0fd 100%);
}
.branch_list_icon{
    position: relative;
    margin-left: 10px;
    padding-left: 10px;
    padding-right: 10px;
    top: 5px;
    background-image: linear-gradient(to right, #ace0f9 0%, #e7f0fd 100%);
    font-size: 20px;
    color: #ff6a00;
    cursor: pointer;
}
.branch_list_icon :hover{
    color: crimson;
}
.branch_list_p{
    font-size: 14px;
    color: #999;
    margin-top: 10px;
    margin-left: 20px;
    overflow: hidden;
    text-overflow: ellipsis;

}
.branch_list_b:hover{
    //background-color: rgba(10, 161, 237, 0.7);
    border:0;
    transition: 0.3s;
    background-image: linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%);
    color: red;

}


/*地图上的按钮*/
ul li {
    list-style: none;
}
.btn-wrap {
    z-index: 999;
    position: fixed;
    bottom: 3.5rem;
    margin-left: 3rem;
    padding: 1rem 1rem;
    border-radius: .25rem;
    background-color: #fff;
    box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
}
.btn {
    width: 75px;
    height: 30px;
    float: left;
    background-color: #fff;
    color: rgba(27, 142, 236, 1);
    font-size: 14px;
    border:1px solid rgba(27, 142, 236, 1);
    border-radius: 5px;
    margin: 0 5px;

    text-align: center;
    line-height: 30px;
}
.btn:hover {
    background-color: rgba(27, 142, 236, 0.8);
    color: #fff;
    cursor: pointer;
}


/*info window里的按钮*/
.info_window_button{
    width: 60px;
    height: 36px;
    background-color: #0aa1ed;
    color: #666;
    border: 0;
    cursor: pointer;
}

</style>